<template>
  <!-- 添加或修改流程定义对话框 -->
  <el-dialog v-model="open" :fullscreen="true" :close-on-press-escape="false" append-to-body>
    <div class="proc-container">
      <div class="header">
        <div class="label center" :class="{selected: stepIndex === 1}" @click="selectStep(1)">1. 基本信息</div>
        <div class="label center" :class="{selected: stepIndex === 2}" @click="selectStep(2)">2. 表单设计</div>
        <div class="label center" :class="{selected: stepIndex === 3}" @click="selectStep(3)">3. 流程设计</div>
        <div class="label center" :class="{selected: stepIndex === 4}" @click="selectStep(4)">4. 高级设置</div>
        <div class="label right">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="publish">发 布</el-button>
        </div>
      </div>
      <div class="body">
        <div class="base" v-show="stepIndex === 1">
          <el-form ref="procRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="流程名称" prop="procName">
              <el-input v-model="form.procName" placeholder="请输入流程名称" />
            </el-form-item>
            <el-form-item label="分组" prop="groupId">
              <el-select v-model="form.groupId" placeholder="请选择分组" clearable style="width: 100%">
                <el-option v-for="group in groupList" :key="group.groupId" :label="group.groupName" :value="group.groupId"/>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="form" v-show="stepIndex === 2">
          <v-form-designer ref="vfDesigner" :designer-config="designerConfig" :banned-widgets="bannedWidgets"></v-form-designer>
        </div>
        <div class="process" v-show="stepIndex === 3">
          <!--            <ProcessDesigner ref="process" :data="data.form"/>-->
          <ProcessDesigner ref="process" :nodeData="nodeData" :formFieldData="formFieldData"/>
        </div>
        <div class="advanced" v-show="stepIndex === 4">
          <div class="row">
            <div class="item">
              <div class="item-header">
                <img class="icon" :src="setupIcon" />
                <div class="name">自动去重</div>
                <div class="switch">
                  <el-switch v-model="form.allowAutoApprove" :active-value="1" :inactive-value="0"/>
                </div>
              </div>
              <div class="explain">审批流程中审批人重复出现时，只需审批一次其余自动通过(仅依次审批类型生效)</div>
            </div>

            <div class="item">
              <div class="item-header">
                <img class="icon" :src="setupIcon" />
                <div class="name">允许加签</div>
                <div class="switch">
                  <el-switch v-model="form.allowAddSign" :active-value="1" :inactive-value="0" />
                </div>
              </div>
              <div class="explain">开启后审批单可以新增临时审批人</div>
            </div>
          </div>

          <div class="row">
            <div class="item">
              <div class="item-header">
                <img class="icon" :src="setupIcon" />
                <div class="name">允许转交</div>
                <div class="switch">
                  <el-switch v-model="form.allowForward" :active-value="1" :inactive-value="0" />
                </div>
              </div>
              <div class="explain">审批流程中审批人可以将当前审批转交给他人进行审批</div>
            </div>

            <div class="item">
              <div class="item-header">
                <img class="icon" :src="setupIcon" />
                <div class="name">允许回退</div>
                <div class="switch">
                  <el-switch v-model="form.allowRollback" :active-value="1" :inactive-value="0" />
                </div>
              </div>
              <div class="explain">审批流程中审批人可以将审批退回至之前的节点</div>
            </div>
          </div>

          <div class="row">
            <div class="item">
              <div class="item-header">
                <img class="icon" :src="setupIcon" />
                <div class="name">允许撤消</div>
                <div class="switch">
                  <el-switch v-model="form.allowRevoke" :active-value="1" :inactive-value="0" />
                </div>
              </div>
              <div class="explain">允许申请人撤消审批申请</div>
            </div>

            <div class="item">
              <div class="item-header">
                <img class="icon" :src="setupIcon" />
                <div class="name">允许审批意见为空</div>
                <div class="switch">
                  <el-switch v-model="form.allowOpinionEmpty" :active-value="1" :inactive-value="0" />
                </div>
              </div>
              <div class="explain">审批时审批意见是否允许为空</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import setupIcon from "@/assets/images/bpm/setup.png";
import ProcessDesigner from "@/components/EasyProcess/ProcessDesigner.vue";
import {getCurrentInstance, nextTick, reactive, ref, toRefs, defineEmits} from "vue";
import {addProc, getProc, updateProc} from "@/api/bpm/proc";
import {listGroup} from "@/api/bpm/group";

const { proxy } = getCurrentInstance();

const emit = defineEmits(["close"]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const groupList = ref([]);
const formFields = ref([]);
const permissions = ref([]);
const nodeData = ref(null);
const formFieldData = ref([]);


/**
 * 步骤索引
 * 1-填写基本信息
 * 2-定义form表单
 * 3-定义审批流程
 * */
const stepIndex = ref(1);

const data = reactive({
  form: {
    test: 1,
    formFields: []
  },
  rules: {
    procName: [
      { required: true, message: "流程名称不能为空", trigger: "blur" }
    ],
    groupId: [
      { required: true, message: "分组不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


// 表单设计器ref
const vfDesigner = ref(null)
// 禁止显示的表单组件
const bannedWidgets = ref([
  'html-text',
  'button',
  'rich-editor',
  'tab',
  'card',
])
// 配置设计器初始化界面显示设置
const designerConfig = reactive({
  languageMenu: false,
  externalLink: false,
  formTemplates: false,
  eventCollapse: false,
  clearDesignerButton: false,
  previewFormButton: true,
  //是否显示导入JSON按钮
  importJsonButton: false,
  //是否显示导出JSON器按钮
  exportJsonButton: false,
  //是否显示导出代码按钮
  exportCodeButton: false,
  //是否显示生成SFC按钮
  generateSFCButton: false,
  removeFieldWidgetBefore: removeFieldWidgetBefore,
  listenerFieldWidgetListChange: listenerFieldWidgetListChange,
  undoHistoryStepBefore: undoHistoryStepBefore,
})


// 取消按钮
function cancel() {
  reset()
  close()
}

// 表单重置
function reset() {
  form.value = {
    procId: null,
    procName: null,
    groupId: null,
    formConfig: null,
    nodeConfig: null,
    allowAddSign: 1,
    allowForward: 1,
    allowRollback: 1,
    allowAutoApprove: 1,
    allowRevoke: 1,
    allowOpinionEmpty: 1,
  };
  proxy.resetForm("procRef");
  stepIndex.value = 1
  nodeData.value = null
}


/**
 * 选择步骤
 */
function selectStep(step) {
  stepIndex.value = step
  // if (step === 3) {
  //   getFormFields()
  // }
}

/**
 * 获取表单字段
 */
function getFormFields() {
  if (vfDesigner.value) {
    let fieldWidgets = vfDesigner.value.getFieldWidgets()
    let fields = []
    if (fieldWidgets) {
      fieldWidgets.forEach(item => {
        fields.push({
          type: item.type,
          name: item.name,
          label: item.field.options.label,
          required: item.field.options.required,
          isCondition: isCondition(item.type),
          optionItems: item.field.options.optionItems
        })
      })
    }
    formFields.value = fields;
    formFieldData.value = fields
  }

}

/**
 * 判断字段是否可做为条件
 * @param type
 * @returns {boolean}
 */
function isCondition(type) {
  return type === 'number' || type === 'checkbox' || type === 'select' || type === 'radio';
}

/**
 * 发布流程
 */
function publish() {
  proxy.$refs["procRef"].validate(valid => {
    if (valid) {
      proxy.$refs.process.validate((processValid, messages) => {
        if(processValid) {
          let nodeConfig = proxy.$refs.process.getResult();
          console.info("发布流程:", nodeConfig)
          form.value.nodeConfig = nodeConfig

          let formConfig = vfDesigner.value.getFormJson()
          console.info("formConfig:", formConfig)
          form.value.formConfig = formConfig

          if (form.value.procId != null) {
            updateProc(form.value).then(response => {
              proxy.$modal.msgSuccess("修改成功");
              close()
            });
          } else {
            addProc(form.value).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              close()
            });
          }
        } else {
          console.error("发布流程ERROR:", messages)
          proxy.$modal.msgError("请完善流程设计");
        }
      })
    } else {
      proxy.$modal.msgError("请完善基本信息填写");
    }
  });


}

/** 查询流程分组列表 */
function getGroupList() {
  listGroup().then(response => {
    groupList.value = response.data;
  });
}

function removeFieldWidgetBefore(fieldName) {
  let isUsed = proxy.$refs.process.getProcessCtrl().isUsedConditionField(fieldName)
  if (isUsed) {
    proxy.$modal.msgError("该字段已做为审批条件使用，不能删除！");
    return false
  }
  return true
}

function listenerFieldWidgetListChange(widgetList) {
  getFormFields()
}
function undoHistoryStepBefore(currentWidgetList, newWidgetList, currentFormConfig, newFormConfig) {
  let removeFieldList = []
  for (let i=0; i<currentWidgetList.length; i++) {
    let currentWidget = currentWidgetList[i]
    let removed = true
    for (let j=0; i<newWidgetList.length; j++) {
      let newWidget = newWidgetList[j]
      if (currentWidget.options.name === newWidget.options.name) {
        removed = false
        break
      }
    }
    if (removed) {
      removeFieldList.push(currentWidget.options.name)
    }
  }

  for (let i=0; i<removeFieldList.length; i++) {
    let field = removeFieldList[i]
    let isUsed = proxy.$refs.process.getProcessCtrl().isUsedConditionField(field)
    if (isUsed) {
      proxy.$modal.msgError(`字段${field}已做为审批条件使用，不能删除！`);
      return false
    }
  }
  return true
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  nextTick(() => {
    vfDesigner.value.clearDesigner()
  })
}

/** 修改按钮操作 */
function handleUpdate(procId) {
  reset();
  getProc(procId).then(response => {
    let data = response.data;
    form.value = data;
    nodeData.value = data.nodeConfig
    open.value = true;
    nextTick(() => {
      vfDesigner.value.setFormJson(data.formConfig)
      getFormFields()
    })

  });
}

function show(procId) {
  getGroupList()
  if (procId == null) {
    handleAdd()
  } else {
    handleUpdate(procId)
  }
}

function close() {
  open.value = false;
  emit("close");
}

defineExpose({
  show,
});
</script>

<style scoped lang="less">
.proc-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;

}
.header {
  position: fixed;
  z-index: 2;
  width: 100%;
  height: 50px;
  background-color: #1c84c6;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0px 16px;
  box-sizing: border-box;

  .label {
    color: #FFFFFF;
    font-weight: bold;
    width: 100px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }


  .center {
    cursor: pointer;
  }
  .right {
    width: 200px;
    position: absolute;
    right: 10px;
  }
  .selected {
    background-color: #084e7b;
  }

}
.body {
  position: absolute;
  top: 0;
  left: 0;
  padding: 66px 16px 16px 16px;
  //width: 100%;
  min-width: 100%;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #F2F3F5;

  .base {
    width: 700px;
    height: 100%;
    margin: 0 auto;
    background-color: #FFFFFF;
    padding: 18px;
    border-radius: 10px;
  }
  .form {
    width: 100%;
    height: 100%;

    /deep/.main-header {
      display: none!important;
    }
  }
  .process {
    width: 100%;
    height: 100%;
  }
  .advanced {
    width: 700px;
    height: 100%;
    margin: 0 auto;
    background-color: #FFFFFF;
    padding: 18px;
    border-radius: 10px;

    .row {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 18px;

      .item {
        width: 320px;
        height: 130px;
        background-color: #FFFFFF;
        padding: 18px;
        border: 1px solid #CDD0D6;
        border-radius: 10px;

        .item-header {
          width: 100%;
          display: flex;
          flex-direction: row;
          align-items: center;
          height: 40px;
          .icon {
            width: 25px;
            height: 25px;
            background-color: #409EFF;
            padding: 5px;
            border-radius: 5px;
          }
          .name {
            flex: 1;
            font-size: 14px;
            color: #303133;
            padding-left: 10px;
          }
          .switch {
            margin-left: auto;
          }
        }
        .explain {
          margin-top: 10px;
          font-size: 12px;
          color: #606266;
        }

      }
    }

  }
}
</style>